package com.async.designpatterns.create.singleton;

/**
 * Created by wenzhuo on 2018/1/1.
 */
public class Singleton {

    private static Singleton instance;

    //注意，构造函数对外封闭，保证实体对象的单例存在
    private Singleton(){

    }

    public void method1(){
        System.out.println("单例对象"+this.hashCode()+"执行方法!");
    }

    //1、通过同步关键字保证线程安全，可能存在指令重排问题，导致null异常
    public static synchronized Singleton getInstance(){
        if (null==instance){
            instance = new Singleton();
        }
        return instance;
    }

    //2、通过jvm类加载机制保证线程安全
    private static class SingletonFactory{
        private static Singleton instance = new Singleton();
    }

    public static Singleton getStaticInstance(){
        return SingletonFactory.instance;
    }

}
